//
//  DHRegistViewController.m
//  精品酒店
//
//  Created by DIANGHONG on 2018/5/8.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "DHRegistViewController.h"

@interface DHRegistViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *nameTextView; // 名称TextField
@property (weak, nonatomic) IBOutlet UITextField *phoneTextView;  // 手机号TextField
@property (weak, nonatomic) IBOutlet UITextField *confirmCodeTextView; // 验证码TextField
@property (weak, nonatomic) IBOutlet UITextField *pwdTextView; // 密码 TextField
@property (weak, nonatomic) IBOutlet UIButton *rigestButton; // 注册按钮
@property (weak, nonatomic) IBOutlet UIButton *getConfirmCodeButton; // 获取验证码按钮
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *getConfirmCodeBtnConsW; // 获取验证码宽度约束

@end

@implementation DHRegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.rigestButton.layer.masksToBounds = true;
    self.rigestButton.layer.cornerRadius = 10;
    [self.rigestButton addTarget:self action:@selector(rigestButtonClick) forControlEvents:UIControlEventTouchUpInside];
    self.phoneTextView.delegate = self;
    self.pwdTextView.secureTextEntry = YES;
    [self.nameTextView becomeFirstResponder];
}
#pragma mark: - 开启倒计时效果
-(void)openCountdownWithTime:(NSInteger)downTime{
    
    __block NSInteger time = downTime; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [self.getConfirmCodeButton setTitle:@"重新发送" forState:UIControlStateNormal];
                self.getConfirmCodeButton.userInteractionEnabled = YES;
            });
            
        }else{
            
            int seconds = time % 120;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果
                [self.getConfirmCodeButton setTitle:[NSString stringWithFormat:@"重新发送(%.2d)", seconds] forState:UIControlStateNormal];
                
                self.getConfirmCodeButton.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}

#pragma mark: - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    return [self validateNumber:string];
}
#pragma mark: - 判断只输入数字的方法
- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}


#pragma mark: - 注册 按钮监听
- (void)rigestButtonClick
{
    [DHNetworkManager.shareManager
     requestToRigestAccountWithUserName:self.nameTextView.text
                                phone:self.phoneTextView.text
                                secret:self.confirmCodeTextView.text
                                password:self.pwdTextView.text
                                completion:^(NSString *statusInfo,BOOL isSuccess)
    {
        if (!isSuccess)
        {
            [SVProgressHUD showErrorWithStatus:statusInfo];
            return ;
        }
        
        [SVProgressHUD showSuccessWithStatus:@"注册成功"];
        
        [self.navigationController popViewControllerAnimated:true];
        
        NSAssert(self.RegistSuccessBlock != nil, @"self.RegistSuccessBlock 不能为nil");
        
        self.RegistSuccessBlock(statusInfo);
    }];
}
#pragma mark: - touchesBegan
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:true];
}
#pragma mark: - 获取验证码按钮监听
- (IBAction)getConfirmCodeClick {
    if ([self.phoneTextView.text isEqualToString:@""]) {return;}
//    [DHNetworkManager.shareManager getPhoneConfirmCode:self.phoneTextView.text];
    [DHNetworkManager.shareManager getPhoneConfirmCode:self.phoneTextView.text
                                            completion:^(NSString *statusInfo, BOOL isSuccess)
    {
        if (!isSuccess)
        {
            [SVProgressHUD showErrorWithStatus:statusInfo];
            return ;
        }
        self.getConfirmCodeBtnConsW.constant += 20;
        [self.getConfirmCodeButton layoutIfNeeded];
        [self openCountdownWithTime:statusInfo.integerValue];
        
    }];
    
}
#pragma mark: - 返回按钮监听
- (IBAction)popButtonClick:(id)sender
{
    [self.navigationController popViewControllerAnimated:true];
}


@end
